#include <stdlib.h>
#include <stdio.h>
#include "pcb.h"
#include "stats.h"
#include "sim.h"

/*global clock */
unsigned clock;

unsigned executed_programs = 0;
unsigned utilized_time;
unsigned long total_run_time;

unsigned min_complete_time = 0;
unsigned max_complete_time;

unsigned last_clock;

static void utilizationTime(unsigned utilized_clock)
{
	utilized_time += utilized_clock;
}

void completed(PCB* pcb)
{
	unsigned start_time = getStartTime(pcb);

	if(0 == clock) {
		fprintf(stderr, "Invalid zero clock for process completed time.\n");
		exit(EXIT_FAILURE);
	}

	utilizationTime(getCompletedTime(pcb));

	total_run_time += ( clock - start_time ); /* measure from start of clock */ 

	if( min_complete_time > (clock - start_time ) || 0 == min_complete_time){
		min_complete_time = (clock - start_time );
	}

	if( max_complete_time < (clock - start_time ) ){
		max_complete_time = (clock - start_time );
	}

	if(debug) printf("\tCOMPLETED:%s PID:%u\n", pcb->name, pcb->pid);

	destroyPCB(pcb);

	executed_programs++;
}

void setLastClock(unsigned last)
{
	last_clock = last;
}

void printStats()
{
	
	fprintf(stderr,"Executed Programs:%d\n", executed_programs);
	fprintf(stderr,"Clock:%u Real Time(sec):%.3f\n", last_clock, last_clock/1000.0);
	fprintf(stderr,"Min/Avg/Max Complete Time (sec):%.3f/%.3f/%.3f\n",
		min_complete_time/1000.0,
		(total_run_time/executed_programs)/1000.0,
		max_complete_time/1000.0);
	fprintf(stderr,"Throughput  (prog/sec):%.3f\n",
		executed_programs/(last_clock/1000.0));
	fprintf(stderr, "Utilization Total(sec):%.3f %%:%.2f\n", 
		utilized_time/1000.0,
		(utilized_time/1000.0)/(last_clock/1000.0)*100.0);
	fprintf(stderr, "Following is for spreadsheet row\n");
	fprintf(stderr, "%.1f\t%u\t%u\t%.3f\t%.2f\t%u\n",
		total_run_time/executed_programs*1.0,
		min_complete_time,
		max_complete_time,
		executed_programs/(last_clock/1000.0),
		(utilized_time/1000.0)/(last_clock/1000.0)*100.0,
		last_clock);
}

